pub = './public'

module.exports = (grunt) ->
  grunt.initConfig
    clean:
      pub: [
        pub
        './db.json'
      ]

    connect:
      svr:
        options:
          port: 80
          base: pub
          keepalive: true
          open: 'http://localhost'

    exec:
      gen: 'hexo g'
      svr: 'hexo s'
      post: 'hexo n post ' + new Date().getTime()

    autoprefixer:
      options:
        browsers: [
          'last 4 versions'
          '> 5%'
          'ff ESR'
          'ie >= 9'
        ]
      pub:
        expand: true
        cwd: pub
        src: '**/*.css'
        dest: pub

    cssmin:
      pub:
        expand: true
        cwd: pub
        src: '**/*.css'
        dest: pub

    uglify:
      pub:
        expand: true
        cwd: pub
        src: '**/*.js'
        dest: pub

    htmlmin:
      options:
        removeComments: true
        removeCommentsFromCDATA: true
        collapseBooleanAttributes: true
        removeAttributeQuotes: true
        removeRedundantAttributes: true
        useShortDoctype: true
        removeEmptyAttributes: true
        minifyJS: true
        minifyCSS: true
      html:
        expand: true
        cwd: pub
        src: '**/*.html'
        dest: pub

    replace:
      htmlmin:
        options:
          patterns: [
            {
              match: /^\s*[\r\n]/gm # 空行
              replacement: ''
            }
            {
              match: /^\s+/gm # 行首空格
              replacement: ''
            }
            {
              match: /\s+$/gm # 行末空格
              replacement: ''
            }
          ]
        files: [
          {
            expand: true
            cwd: pub
            src: '**/*.html'
            dest: pub
          }
        ]

  require('load-grunt-tasks')(grunt)

  grunt.registerTask 'default', [
    'clean'
    'exec:gen'
    'autoprefixer'
    'cssmin'
    'uglify'
    'htmlmin'
    'replace'
  ]

  grunt.registerTask 'server', [
    'exec:svr'
  ]

  grunt.registerTask 'post', [
    'exec:post'
  ]

  grunt.registerTask 'preview', [
    'default'
    'connect'
  ]
